package com.borya.service.mobile.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.borya.constant.RedisConstant;
import com.borya.dao.MerchantDAO;
import com.borya.dao.MerchantFillServiceDAO;
import com.borya.dao.RegistOrderInfoDAO;
import com.borya.filter.auth.AppSignTokenVersion;
import com.borya.framework.annotation.Autowired;
import com.borya.framework.annotation.Component;
import com.borya.model.db.Merchant;
import com.borya.model.db.MerchantInfoFill;
import com.borya.model.db.ReplenishModel;
import com.borya.model.db.User;
import com.borya.model.db.UserClientDetail;
import com.borya.model.entity.HeaderEntity;
import com.borya.service.impl.BaseServiceImpl;
import com.borya.service.mobile.MerchantFillService;
import com.borya.statuscode.StatusCode;
import com.borya.util.AliOSSUtil;
import com.borya.util.CityUtils;
import com.borya.util.Constant;
import com.borya.util.Constant.RegisterAuditOrderStatus;
import com.borya.util.DateUtils;
import com.borya.util.StringUtil;
import com.borya.util.SystemConfig;

@Component("merchantFillService")
public class MerchantFillServiceImpl extends BaseServiceImpl implements MerchantFillService {

	private Logger log = Logger.getLogger(getClass());

	@Autowired("merchantFillServiceDAO")
	private MerchantFillServiceDAO merchantFillServiceDAO;

	@Autowired("registOrderInfoDAO")
	private RegistOrderInfoDAO registOrderInfoDAO;
	@Autowired("merchantDAO")
	private MerchantDAO merchantDAO;

	@Override
	public String getStatus(User user) {
		final String merchantId = user.getMerchantId();
		int status = merchantDAO.getfillStatus(merchantId);
		if (status == -1) {
			log.error("商户不存在,merchantId=" + merchantId);
			return StatusCode.SYSTEM_EXCEPTION.toJSON("网络异常,商户查找异常");
		}
		JSONObject json = new JSONObject();
		json.put("fillStatus", String.valueOf(status));

		return StatusCode.SUCCESS.toDiyJson("data", json);
	}

	@Override
	public String getInfo(User user) {
		int status = merchantDAO.getfillStatus(user.getMerchantId());
		switch (status) {// 0正常1待补登2成功3失败4进行中
		case 0:
		case 2:
			log.debug("商户已通过实名补录,merchantId=" + user.getMerchantId());
			return StatusCode.UNKNOWN.toJSON("商户已通过实名补录");
		case 1:
		case 3:
			break;
		case 4:
			log.debug("商户已提交实名补录,merchantId=" + user.getMerchantId());
			return StatusCode.UNKNOWN.toJSON("商户已提交实名补录,请等待消息通知");
		default:
			break;
		}

		if (user.getIsMain() == 0) {
			log.warn("子账号不允许实名补录,user=" + user.getUserId());
			return StatusCode.UNKNOWN.toJSON("请联系主工号进行实名补录");
		}

		MerchantInfoFill merchantInfo = merchantFillServiceDAO.getLast(user.getMerchantId());
		if (merchantInfo == null || merchantInfo == null) {
			log.error("DB数据异常,merhantId=" + user.getMerchantId());
			return StatusCode.SYSTEM_EXCEPTION.toJSON("网络连接异常");
		}
		if (Objects.isNull(merchantInfo.getMerchantId())) {
			log.error("DB无商户补录信息,merhantId=" + user.getMerchantId());
			return StatusCode.SYSTEM_EXCEPTION.toJSON("网络连接异常");
		}
		Merchant merchant = merchantDAO.getByMerchantId(user.getMerchantId());
		if (Objects.isNull(merchant)) {
			log.error("商户不存在,merchantId=" + user.getMerchantId());
			return StatusCode.SYSTEM_EXCEPTION.toJSON();
		}
		UserClientDetail userClientDetail = merchantDAO.getUserClientDetailByMerchantId(user.getUserId());
		if (Objects.isNull(userClientDetail)) {
			log.error("商户详情不存在,merchantId=" + user.getMerchantId());
			return StatusCode.SYSTEM_EXCEPTION.toJSON();
		}

		JSONObject json = new JSONObject();
		json.put("orderId", merchantInfo.getOrderId());
		json.put("merchantType", merchantInfo.getMerchantType());
		json.put("companyName", merchantInfo.getCompanyName());
		json.put("address", merchantInfo.getAddress());
		json.put("userName", merchantInfo.getUserName());
		json.put("storeAddress", merchantInfo.getStoreAddress());
		// json.put("signPicture", merchantInfo.getSignPicture());
		json.put("doorPictureLeft",
				AliOSSUtil.generatePresignedUrl(AliOSSUtil.getDownloadUrl(merchantInfo.getDoorPictureLeft())));
		json.put("doorPictureRight",
				AliOSSUtil.generatePresignedUrl(AliOSSUtil.getDownloadUrl(merchantInfo.getDoorPictureRight())));
		json.put("handPicture",
				AliOSSUtil.generatePresignedUrl(AliOSSUtil.getDownloadUrl(merchantInfo.getHandPicture())));
		json.put("businessLicence", merchantInfo.getBusinessLicence());
		json.put("cityCode", merchantInfo.getCityCode());
		json.put("cityName", merchantInfo.getCityName());
		json.put("period", merchantInfo.getPeriod());
		json.put("remark", "拒绝原因:" + merchantInfo.getRemarks());
		json.put("shopAddress",
				StringUtils.isNotBlank(merchantInfo.getShopAddress()) ? merchantInfo.getShopAddress() : "");
		json.put("shopSpecificAddress", StringUtils.isNotBlank(merchantInfo.getShopSpecificAddress())
				? merchantInfo.getShopSpecificAddress() : "");
		if (StringUtils.isNotBlank(merchantInfo.getIdentifyPhotoFront())) {
			json.put("identifyPhotoFront",
					AliOSSUtil.generatePresignedUrl(AliOSSUtil.getDownloadUrl(merchantInfo.getIdentifyPhotoFront())));
		}
		if (StringUtils.isNotBlank(merchantInfo.getIdentifyPhotoReverse())) {
			json.put("identifyPhotoReverse",
					AliOSSUtil.generatePresignedUrl(AliOSSUtil.getDownloadUrl(merchantInfo.getIdentifyPhotoReverse())));
		}
		if (StringUtils.isNotBlank(merchantInfo.getIdentifyPhotoHand())) {
			json.put("identifyPhotoHand",
					AliOSSUtil.generatePresignedUrl(AliOSSUtil.getDownloadUrl(merchantInfo.getIdentifyPhotoHand())));
		}
		if (1 == merchant.getMerchantType()) {
			// 企业
			json.put("identityCard", userClientDetail.getIdentityCard());
			json.put("identityCardAddress", userClientDetail.getIdentityCardAddress());
			json.put("identityCardName", userClientDetail.getIdentityCardName());
		} else {
			// 个人
			json.put("identityCard", merchant.getBusinessLicence());
			json.put("identityCardAddress", merchant.getAddress());
			json.put("identityCardName", merchant.getCompanyName());
		}

		return StatusCode.SUCCESS.toDiyJson("data", json);
	}

	/**
	 * 组装网络路径
	 * 
	 * @param url
	 * @return
	 */
	// private String parseNetUrl(String url) {
	// if (url == null || url.trim().length() == 0) {
	// return "";
	// }
	// if (url.startsWith("/")) {
	// return Constant.ums_url + url;
	// }
	// if (url.startsWith(Constant.ums_url)) {
	// return url;
	// }
	//
	// if (url.substring(0, 4).equals("http")) {
	// return url;
	// }
	// return Constant.ums_url + url;
	// }

	// final String fillDir = "/registing/";

	// @Override
	// public String upload(User user, JSONObject json) {
	// final String merchantId = user.getMerchantId();
	// final String imgBase64 = json.getString("img");
	// final String YYMMddHHmmssSSS = DateUtils.format("YYMMddHHmmssSSS");
	// final String dir = fillDir + merchantId + "/";
	// final String imgName = merchantId + "_"+YYMMddHHmmssSSS+ ".png";
	//
	// try {
	// boolean ok = ImageUtils.writeImg(dir, imgName, imgBase64);
	// if(!ok){
	// return StatusCode.PARAM_ERROR.toJSON("文件读写异常");
	// }
	// } catch (IOException e) {
	// log.error(e.getMessage(),e);
	// }
	// //TODO 文件加水印
	// JSONObject jonObj = new JSONObject();
	// jonObj.put("imgPath", dir+imgName);
	// return StatusCode.SUCCESS.toDiyJson("data", jonObj);
	// }

	@Override
	public String add(User user, MerchantInfoFill infoFill) {
		final String merchantId = user.getMerchantId();
		final String YYMMddHHmmss = DateUtils.format("YYMMddHHmmss");
		final String orderId = Constant.MERCHANT_ORDER_PREFIX + YYMMddHHmmss + StringUtil.randomNumberString(4);

		final String boryaAuthStr = infoFill.getBoryaAuth();
		HeaderEntity authHeader = JSONObject.parseObject(boryaAuthStr, HeaderEntity.class);
		if (authHeader.getAppVersion() >= infoFill.getBackgroundVersion()) {
			if (StringUtil.isNULL(infoFill.getShopAddress())) {
				log.error("param shopAddress is null");
				return StatusCode.PARAM_ERROR.toJSON("地区不能为空");
			}
			if (StringUtil.isNULL(infoFill.getShopSpecificAddress())) {
				log.error("param shopSpecificAddress is null");
				return StatusCode.SYSTEM_EXCEPTION.toJSON("具体地址不能为空");
			}
		}

		MerchantInfoFill infoFillDB = merchantFillServiceDAO.getLast(merchantId);
		if (infoFillDB == null) {
			log.error("DB连接异常");
			return StatusCode.SYSTEM_EXCEPTION.toJSON();
		}
		if (Objects.isNull(infoFillDB.getOrderId())) {
			log.error("DB数据异常,(tb_registor_audit)userId=" + user.getUserId());
			return StatusCode.SYSTEM_EXCEPTION.toJSON("数据异常,请联系管理员");
		}

		Merchant merchant = merchantDAO.getByMerchantId(merchantId);
		if (merchant == null) {
			log.error("DB连接异常");
			return StatusCode.SYSTEM_EXCEPTION.toJSON();
		}
		final int userType = merchant.getUserTypeId();
		String nickName = merchantDAO.getUserTypeNickName(userType);

		final String signPicture = infoFill.getSignPicture();

		infoFill.setOrderId(orderId);
		infoFill.setRegistOrderId(infoFillDB.getOrderId());
		infoFill.setCreateTime(System.currentTimeMillis());
		infoFill.setUserId(user.getUserId());
		infoFill.setDealerId(infoFillDB.getDealerId());
		infoFill.setMerchantType(infoFillDB.getMerchantType());
		if (infoFillDB.getMerchantType() == 2) {
			infoFill.setCompanyName(infoFill.getUserName());
		}
		infoFill.setOrderStatus(RegisterAuditOrderStatus.WAIT_AUDIT);
		infoFill.setMerchantId(user.getMerchantId());
		// 图片兼容变成网路径
		String left = "", right = "", hand = "", headPicture = "", signMergePicture1 = "", signPicture1 = "";
		if (StringUtils.isNotBlank(infoFill.getDoorPictureLeft())) {
			left = (infoFill.getDoorPictureLeft().substring(0, infoFill.getDoorPictureLeft().lastIndexOf(".")))
					+ ".png";
			if (left.contains("http")) {
				left = ((left.substring(left.lastIndexOf("com"), left.lastIndexOf("."))) + ".png").substring(3);
			}
		}
		if (StringUtils.isNotBlank(infoFill.getDoorPictureRight())) {
			right = (infoFill.getDoorPictureRight().substring(0, infoFill.getDoorPictureRight().lastIndexOf(".")))
					+ ".png";
			if (right.contains("http")) {
				right = ((right.substring(right.lastIndexOf("com"), right.lastIndexOf("."))) + ".png").substring(3);
			}
		}
		if (StringUtils.isNotBlank(infoFill.getHandPicture())) {
			hand = (infoFill.getHandPicture().substring(0, infoFill.getHandPicture().lastIndexOf("."))) + ".png";
			if (hand.contains("http")) {
				hand = ((hand.substring(hand.lastIndexOf("com"), hand.lastIndexOf("."))) + ".png").substring(3);
			}
		}
		if (StringUtils.isNotBlank(infoFillDB.getHeadPicture())) {
			headPicture = (infoFillDB.getHeadPicture().substring(0, infoFillDB.getHeadPicture().lastIndexOf(".")))
					+ ".png";
			if (headPicture.contains("http")) {
				headPicture = ((headPicture.substring(headPicture.lastIndexOf("com"), headPicture.lastIndexOf(".")))
						+ ".png").substring(3);
			}
		}
		if (StringUtils.isNotBlank(infoFill.getSignMergePicture())) {
			signMergePicture1 = (infoFill.getSignMergePicture().substring(0,
					infoFill.getSignMergePicture().lastIndexOf("."))) + ".png";
			if (signMergePicture1.contains("http")) {
				signMergePicture1 = ((signMergePicture1.substring(signMergePicture1.lastIndexOf("com"),
						signMergePicture1.lastIndexOf("."))) + ".png").substring(3);
			}
		}
		if (StringUtils.isNotBlank(infoFill.getSignPicture())) {
			signPicture1 = (infoFill.getSignPicture().substring(0, infoFill.getSignPicture().lastIndexOf(".")))
					+ ".png";
			if (signPicture1.contains("http")) {
				signPicture1 = ((signPicture1.substring(signPicture1.lastIndexOf("com"), signPicture1.lastIndexOf(".")))
						+ ".png").substring(3);
			}
		}

		infoFill.setHeadPicture(headPicture);
		infoFill.setSignMergePicture(signMergePicture1);
		infoFill.setSignPicture(signPicture1);
		infoFill.setDoorPictureLeft(left);
		infoFill.setDoorPictureRight(right);
		infoFill.setHandPicture(hand);
		infoFill.setCustomer("");
		infoFill.setAutoAuditDesc("");
		infoFill.setGztCheck("");
		infoFill.setPeriod(trimNULL(infoFillDB.getPeriod()));
		infoFill.setRemarks("");
		infoFill.setSourceType(infoFillDB.getSourceType());
		infoFill.setRequestPhone(infoFillDB.getRequestPhone());
		infoFill.setAuditType(1);// 1 实时审核 2 事后审核 3 自动审核
		infoFill.setNickName(nickName);
		if (1 == infoFillDB.getMerchantType()) {
			if (StringUtils.isNotBlank(infoFill.getIdentifyPhotoFront())) {
				String identifyPhotoFront = (infoFill.getIdentifyPhotoFront().substring(0,
						infoFill.getIdentifyPhotoFront().lastIndexOf("."))) + ".png";
				if (identifyPhotoFront.contains("http")) {
					identifyPhotoFront = ((identifyPhotoFront.substring(identifyPhotoFront.lastIndexOf("com"),
							identifyPhotoFront.lastIndexOf("."))) + ".png").substring(3);
				}
				infoFill.setIdentifyPhotoFront(identifyPhotoFront);
			}
			if (StringUtils.isNotBlank(infoFill.getIdentifyPhotoReverse())) {
				String identifyPhotoReverse = (infoFill.getIdentifyPhotoReverse().substring(0,
						infoFill.getIdentifyPhotoReverse().lastIndexOf("."))) + ".png";
				if (identifyPhotoReverse.contains("http")) {
					identifyPhotoReverse = ((identifyPhotoReverse.substring(identifyPhotoReverse.lastIndexOf("com"),
							identifyPhotoReverse.lastIndexOf("."))) + ".png").substring(3);
				}
				infoFill.setIdentifyPhotoReverse(identifyPhotoReverse);
			}
			if (StringUtils.isNotBlank(infoFill.getIdentifyPhotoHand())) {
				String identifyPhotoHand = (infoFill.getIdentifyPhotoHand().substring(0,
						infoFill.getIdentifyPhotoHand().lastIndexOf("."))) + ".png";
				if (identifyPhotoHand.contains("http")) {
					identifyPhotoHand = ((identifyPhotoHand.substring(identifyPhotoHand.lastIndexOf("com"),
							identifyPhotoHand.lastIndexOf("."))) + ".png").substring(3);
				}
				infoFill.setIdentifyPhotoHand(identifyPhotoHand);
			}
		} else {
			if (StringUtils.isNotBlank(left)) {
				infoFill.setIdentifyPhotoFront(left);
			}
			if (StringUtils.isNotBlank(right)) {
				infoFill.setIdentifyPhotoReverse(right);
			}
			if (StringUtils.isNotBlank(hand)) {
				infoFill.setIdentifyPhotoHand(hand);
			}
		}

		int index = signPicture.lastIndexOf("/");
		final String fileName = signPicture.substring(index + 1);
		String signMergePicture = signPicture.substring(0, index + 1) + fileName.replace(".", "_merge.");
		signMergePicture = signMergePicture.replace("_narrow", "");
		infoFill.setSignMergePicture(signMergePicture);

		AutoAuditEntity autoAudit = new AutoAuditEntity();
		autoAudit.setBackImageLocation(infoFill.getDoorPictureRight());
		autoAudit.setFrontImageLocation(infoFill.getDoorPictureLeft());
		autoAudit.setHandImageLocation(infoFill.getHandPicture());
		autoAudit.setHeadImageLocation(infoFill.getHeadPicture());
		autoAudit.setIdCardAddress(infoFill.getAddress());
		autoAudit.setIdCardName(infoFill.getUserName());
		autoAudit.setIdCardNo(infoFill.getBusinessLicence());
		autoAudit.setIdCardPeriod(infoFill.getPeriod());
		autoAudit.setIsp("1");
		autoAudit.setMerchantType(infoFill.getMerchantType());
		autoAudit.setOpenModel("3");// 相册、拍照
		autoAudit.setOrderId(orderId);
		autoAudit.setSource("1");

		final String auditStr = JSONObject.toJSONString(autoAudit);

		// 个人、企业都需要加入redis自动审核
		Long result = merchantFillServiceDAO.redis_rpush(RedisConstant.AUDIT_KEY, auditStr);
		if (result == null) {
			log.error("redis连接异常");
			return StatusCode.SYSTEM_EXCEPTION.toJSON();
		}
		boolean bool = merchantFillServiceDAO.insert(infoFill);
		if (!bool) {
			log.error("数据库异常");
			return StatusCode.SYSTEM_EXCEPTION.toJSON();
		}

		return StatusCode.SUCCESS.toJSON();
	}

	private String trimNULL(String str) {
		if (str == null) {
			return "";
		}
		return str.trim();
	}

	/**
	 * activateLog.setOrderId(object.getString("orderId"));
	 * activateLog.setSource(object.getString("source"));
	 * activateLog.setMerchantType(object.getString("merchantType"));
	 * activateLog.setIsp(object.getString("isp"));
	 * activateLog.setOpenModel(object.getString("openModel"));
	 * activateLog.setIdCardNo(object.getString("idCardNo"));
	 * activateLog.setIdCardName(object.getString("idCardName"));
	 * activateLog.setIdCardAddress(object.getString("idCardAddress"));
	 * activateLog.setIdCardPeriod(object.getString("idCardPeriod"));
	 * activateLog.setFrontImageLocation(object.getString("frontImageLocation"))
	 * ;
	 * activateLog.setBackImageLocation(object.getString("backImageLocation"));
	 * activateLog.setHandImageLocation(object.getString("handImageLocation"));
	 * activateLog.setHeadImageLocation(object.getString("headImageLocation"));
	 * 
	 * @author Administrator
	 *
	 */
	public class AutoAuditEntity {
		private String orderId;
		private String source;// 卡盟为1
		private int merchantType;
		private String isp;
		private String openModel;
		private String idCardNo;
		private String idCardName;
		private String idCardAddress;
		private String idCardPeriod;
		private String frontImageLocation;
		private String backImageLocation;
		private String handImageLocation;
		private String headImageLocation;
		private String orderType;

		public String getOrderId() {
			return orderId;
		}

		public void setOrderId(String orderId) {
			this.orderId = orderId;
		}

		public String getSource() {
			return source;
		}

		public void setSource(String source) {
			this.source = source;
		}

		public int getMerchantType() {
			return merchantType;
		}

		public void setMerchantType(int merchantType) {
			this.merchantType = merchantType;
		}

		public String getIsp() {
			return isp;
		}

		public void setIsp(String isp) {
			this.isp = isp;
		}

		public String getOpenModel() {
			return openModel;
		}

		public void setOpenModel(String openModel) {
			this.openModel = openModel;
		}

		public String getIdCardNo() {
			return idCardNo;
		}

		public void setIdCardNo(String idCardNo) {
			this.idCardNo = idCardNo;
		}

		public String getIdCardName() {
			return idCardName;
		}

		public void setIdCardName(String idCardName) {
			this.idCardName = idCardName;
		}

		public String getIdCardAddress() {
			return idCardAddress;
		}

		public void setIdCardAddress(String idCardAddress) {
			this.idCardAddress = idCardAddress;
		}

		public String getIdCardPeriod() {
			return idCardPeriod;
		}

		public void setIdCardPeriod(String idCardPeriod) {
			this.idCardPeriod = idCardPeriod;
		}

		public String getFrontImageLocation() {
			return frontImageLocation;
		}

		public void setFrontImageLocation(String frontImageLocation) {
			this.frontImageLocation = frontImageLocation;
		}

		public String getBackImageLocation() {
			return backImageLocation;
		}

		public void setBackImageLocation(String backImageLocation) {
			this.backImageLocation = backImageLocation;
		}

		public String getHandImageLocation() {
			return handImageLocation;
		}

		public void setHandImageLocation(String handImageLocation) {
			this.handImageLocation = handImageLocation;
		}

		public String getHeadImageLocation() {
			return headImageLocation;
		}

		public void setHeadImageLocation(String headImageLocation) {
			this.headImageLocation = headImageLocation;
		}

		public String getOrderType() {
			return orderType;
		}

		public void setOrderType(String orderType) {
			this.orderType = orderType;
		}
	}

	@Override
	public String getReplenish(User user, JSONObject json) {
		final String merchantId = user.getMerchantId();
		MerchantInfoFill merchantInfoFill = merchantFillServiceDAO.getMerchantReplenishRecord(merchantId, 0); // order_status=0
																												// 为处理中
		final String boryaAuthStr = json.getString("boryaAuth");
		final String appType = json.getString("appType");
        final String osType = json.getString("osType");
        int backgroundVersion = getBackgroundVersion(appType, osType);
		HeaderEntity authHeader = JSONObject.parseObject(boryaAuthStr, HeaderEntity.class);
		SystemConfig instance = SystemConfig.getInstance();
		if (authHeader.getAppVersion() < backgroundVersion) {
			log.warn("IOS app 版本低于服务器版本,appVersion=" + authHeader.getAppVersion() + ",serverVersion="
					+ instance.getInteger(AppSignTokenVersion.KA_MENG_IOS.getToken()));
			return StatusCode.SYSTEM_EXCEPTION.toJSON("IOS app 版本低于服务器版本");
		}
		if (Objects.nonNull(merchantInfoFill)) {
			log.warn("该商户已经提交申请，正在审批中,merchantId=" + merchantId);
			return StatusCode.SYSTEM_EXCEPTION.toJSON("该商户已经提交申请，正在审批中");
		}
		ReplenishModel model = merchantDAO.getReplenish(merchantId);
		if (Objects.isNull(model)) {
			log.warn("商户信息不存在,merchantId=" + merchantId);
			return StatusCode.NO_CONTENT.toJSON("商户信息不存在");
		}
		if (!model.getStatus().equals(0)) { // 0已激活1待激活2已申请设备3激活审核中
			log.warn("商户未激活,status=" + model.getStatus() + "merchantId=" + merchantId);
			return StatusCode.SYSTEM_EXCEPTION.toJSON("商户未激活，不能操作资料补充");
		}
		String addresses = "", storeAddress = "", sellCityName, sellCityCode, companyName, mainBusiness = "";
		sellCityName = StringUtils.isBlank(model.getSellCityName()) ? "" : model.getSellCityName();
		sellCityCode = StringUtils.isBlank(model.getSellCityCode()) ? "" : model.getSellCityCode();
		companyName = StringUtils.isBlank(model.getCompanyName()) ? "" : model.getCompanyName();
		if (StringUtils.isNotBlank(model.getStoreAddress())) {
			List<Map<String, String>> cityTable = CityUtils.addressResolution(model.getStoreAddress());
			if (!Objects.isNull(cityTable) && cityTable.size() > 0) {
				addresses = cityTable.get(0).get("province") + cityTable.get(0).get("city"); // 门店所在地区
				storeAddress = cityTable.get(0).get("county") + cityTable.get(0).get("town")
						+ cityTable.get(0).get("village");// 门店具体地址
			}

		}

		// 获取相关审核信息
		MerchantInfoFill fill = merchantFillServiceDAO.getMerchantReplenishRecord(merchantId, null);
		int isSuccess = 3; // 审核是否成功，0未审核，1成功，2失败，3空数据
		int state = 1; // 是否可以修改，1是，2否
		String hintCont = ""; // 提示信息
		String doorPictureOut = "";
		String doorPictureIn = "";
		String peoplePicture = "";
		String doorPictureLeft = ""; // 身份证照片正面
		String doorPictureRight = ""; // 身份证照片背面
		String handPicture = ""; // 手持身份证照片
		String businessLicensePicture = "";// 商户营业执照照片
		if (Objects.nonNull(fill)) {
			isSuccess = fill.getOrderStatus();
			if (0 != fill.getAuditTime() && Objects.nonNull(fill.getAuditTime())) {
				String auditTime = DateUtils.format(fill.getAuditTime(), "yyyy-MM-dd HH:mm:ss");
				long againSubmitTimeLong = DateUtils.addDate(fill.getAuditTime(), Constant.AUDIT_EXPIRE_TIME); // 再次提交时间
				String againSubmitTime = DateUtils.format(againSubmitTimeLong, "yyyy-MM-dd HH:mm:ss");
				state = againSubmitTimeLong >= new Date().getTime() ? 2 : 1; // 修改日期距离当前日期小于等于30天则不能再次提交(修改)
				if (fill.getOrderStatus() == 1) {
					hintCont = "您最近一次提交的补充资料已与" + auditTime + "审核通过。如有变更，请" + againSubmitTime + "后点击右上角的'资料变更'进行更改提交。";
				}
				if (fill.getOrderStatus() == 2) {
					hintCont = "您最近一次提交的补充资料已与" + auditTime + "审核未通过。原因：" + fill.getRemarks() + "。";
				}
			}
			doorPictureOut = StringUtils.isBlank(fill.getDoorPictureOut()) ? "" : fill.getDoorPictureOut(); // 照片路径
			doorPictureIn = StringUtils.isBlank(fill.getDoorPictureIn()) ? "" : fill.getDoorPictureIn();
			peoplePicture = StringUtils.isBlank(fill.getPeoplePicture()) ? "" : fill.getPeoplePicture();
			// 以下图片路径为企业商户需要
			doorPictureLeft = StringUtils.isBlank(fill.getDoorPictureLeft()) ? "" : fill.getDoorPictureLeft();
			doorPictureRight = StringUtils.isBlank(fill.getDoorPictureRight()) ? "" : fill.getDoorPictureRight();
			handPicture = StringUtils.isBlank(fill.getHandPicture()) ? "" : fill.getHandPicture();
			businessLicensePicture = StringUtils.isBlank(fill.getBusinessLicensePicture()) ? ""
					: fill.getBusinessLicensePicture();
			state = isSuccess == 2 ? 2 : state;
			if (StringUtils.isBlank(addresses) && StringUtils.isNotBlank(fill.getAddresses())) {
				addresses = fill.getAddresses();
			}
			if (StringUtils.isBlank(storeAddress) && StringUtils.isNotBlank(fill.getStoreAddress())) {
				storeAddress = fill.getStoreAddress();
			}
			if (StringUtils.isBlank(sellCityName) && StringUtils.isNotBlank(fill.getCityName())) {
				sellCityName = fill.getCityName();
			}
			if (StringUtils.isBlank(sellCityCode) && StringUtils.isNotBlank(fill.getCityCode())) {
				sellCityCode = fill.getCityCode();
			}
			if (StringUtils.isBlank(companyName) && StringUtils.isNotBlank(fill.getCompanyName())) {
				companyName = fill.getCompanyName();
			}
			if (StringUtils.isBlank(mainBusiness) && StringUtils.isNotBlank(fill.getMainBusiness())) {
				mainBusiness = fill.getMainBusiness();
			}
		}
		Integer isIdentificationPhoto = 2; // 是否需要上传证件照，1代表是，2代表否(企业商户)
		if (StringUtils.isBlank(doorPictureLeft) && StringUtils.isBlank(doorPictureRight)
				&& StringUtils.isBlank(handPicture) && StringUtils.isBlank(businessLicensePicture)) {
			isIdentificationPhoto = 1;
		}

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("companyName", companyName);
		jsonObject.put("addresses", addresses);// 门店所在地区
		jsonObject.put("storeAddress", storeAddress);// 门店具体地址
		jsonObject.put("sellCityName", sellCityName);// 售卡城市
		jsonObject.put("sellCityCode", sellCityCode);// 售卡城市编码
		jsonObject.put("isSuccess", isSuccess);
		jsonObject.put("state", state);
		jsonObject.put("hintCont", hintCont);
		jsonObject.put("doorPictureOut", AliOSSUtil.generatePresignedUrl(AliOSSUtil.getDownloadUrl((doorPictureOut))));
		jsonObject.put("doorPictureIn", AliOSSUtil.generatePresignedUrl(AliOSSUtil.getDownloadUrl((doorPictureIn))));
		jsonObject.put("peoplePicture", AliOSSUtil.generatePresignedUrl(AliOSSUtil.getDownloadUrl((peoplePicture))));
		jsonObject.put("doorPictureLeft",
				AliOSSUtil.generatePresignedUrl(AliOSSUtil.getDownloadUrl((doorPictureLeft))));
		jsonObject.put("doorPictureRight",
				AliOSSUtil.generatePresignedUrl(AliOSSUtil.getDownloadUrl((doorPictureRight))));
		jsonObject.put("handPicture", AliOSSUtil.generatePresignedUrl(AliOSSUtil.getDownloadUrl((handPicture))));
		jsonObject.put("businessLicensePicture",
				AliOSSUtil.generatePresignedUrl(AliOSSUtil.getDownloadUrl((businessLicensePicture))));
		jsonObject.put("mainBusiness", mainBusiness); // 主营业务（企业商户独有）
		jsonObject.put("merchantType", model.getMerchantType());
		jsonObject.put("isIdentificationPhoto", isIdentificationPhoto);

		return StatusCode.SUCCESS.toDiyJson("data", jsonObject);
	}

	@Override
	public String addReplenish(User user, MerchantInfoFill infoFill) {
		final String merchantId = user.getMerchantId();
		final String YYMMddHHmmss = DateUtils.format("YYMMddHHmmss");
		final String orderId = Constant.MERCHANT_ORDER_PREFIX + YYMMddHHmmss + StringUtil.randomNumberString(4);

		if (0 == infoFill.getMerchantType()) {
			log.error("param merchantType is error");
			return StatusCode.PARAM_ERROR.toJSON("商户类型不正确");
		}
		if (StringUtils.isBlank(infoFill.getCompanyName())) {
			log.error("param companyName is null");
			return StatusCode.PARAM_ERROR.toJSON("门店名称不能为空");
		}
		if (StringUtils.isBlank(infoFill.getAddresses())) {
			log.error("param addresses is null");
			return StatusCode.PARAM_ERROR.toJSON("门店所在地区不能为空");
		}
		if (StringUtils.isBlank(infoFill.getStoreAddress())) {
			log.error("param storeAddress is null");
			return StatusCode.PARAM_ERROR.toJSON("门店具体地址不能为空");
		}
		if (StringUtils.isBlank(infoFill.getDoorPictureOut())) {
			log.error("param doorPictureOut is null");
			return StatusCode.PARAM_ERROR.toJSON("门头照片不能为空");
		}
		if (StringUtils.isBlank(infoFill.getDoorPictureIn())) {
			log.error("param doorPictureIn is null");
			return StatusCode.PARAM_ERROR.toJSON("店内照片不能为空");
		}
		if (StringUtils.isBlank(infoFill.getPeoplePicture())) {
			log.error("param peoplePicture is null");
			return StatusCode.PARAM_ERROR.toJSON("商户本人与门店合照不能为空");
		}
		if (StringUtils.isBlank(infoFill.getCityCode())) {
			log.error("param sellCityCode is null");
			return StatusCode.PARAM_ERROR.toJSON("售卡城市code不能为空");
		}
		if (StringUtils.isBlank(infoFill.getCityName())) {
			log.error("param sellCityName is null");
			return StatusCode.PARAM_ERROR.toJSON("售卡城市不能为空");
		}
		if (1 == infoFill.getMerchantType()) { // 为1代表为企业商户
			if (StringUtils.isBlank(infoFill.getMainBusiness())) {
				log.error("param mainBusiness is null");
				return StatusCode.PARAM_ERROR.toJSON("主营业务不能为空");
			}
			if (StringUtils.isBlank(infoFill.getDoorPictureLeft())) {
				log.error("param storeAddress is null");
				return StatusCode.PARAM_ERROR.toJSON("身份证正面照片不能为空");
			}
			if (StringUtils.isBlank(infoFill.getDoorPictureRight())) {
				log.error("param storeAddress is null");
				return StatusCode.PARAM_ERROR.toJSON("身份证侧面照片不能为空");
			}
			if (StringUtils.isBlank(infoFill.getHandPicture())) {
				log.error("param storeAddress is null");
				return StatusCode.PARAM_ERROR.toJSON("商户手持身份证照片不能为空");
			}
			if (StringUtils.isBlank(infoFill.getBusinessLicensePicture())) {
				log.error("param storeAddress is null");
				return StatusCode.PARAM_ERROR.toJSON("营业执照照片不能为空");
			}
		}

		Merchant merchant = merchantDAO.getByMerchantId(merchantId);
		if (Objects.isNull(merchant)) {
			log.error("DB Connection Exception,merchantId is " + merchantId);
			return StatusCode.SYSTEM_EXCEPTION.toJSON();
		}
		String nickName = merchantDAO.getUserTypeNickName(merchant.getUserTypeId());
		infoFill.setBusinessLicence(
				StringUtils.isBlank(merchant.getBusinessLicence()) ? "" : merchant.getBusinessLicence());
		infoFill.setPeriod(StringUtils.isBlank(merchant.getPeriod()) ? "" : merchant.getPeriod());
		infoFill.setUserTypeId(merchant.getUserTypeId());
		infoFill.setUserTypeName(nickName);
		infoFill.setOrderId(orderId);
		infoFill.setMerchantId(merchantId);
		infoFill.setDealerId(merchant.getDealerId());
		infoFill.setCreateTime(System.currentTimeMillis());
		infoFill.setOrderStatus(0);
		infoFill.setAuditType(2);
		infoFill.setUserId(user.getUserId());

		boolean bool = merchantFillServiceDAO.insertReplenishRecord(infoFill);
		if (!bool) {
			log.error("DB Connection Exception");
			return StatusCode.SYSTEM_EXCEPTION.toJSON();
		}

		return StatusCode.SUCCESS.toJSON();
	}

}